/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mundialfp.view.encuentro;

import core.IntegerDocumentFilter;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.PlainDocument;
import mundialfp.view.main.PrincipalManager;
import mundialfp.view.tables.paisABM.PaisABMTableModel;
import mundialfp.view.tables.PaisTableModel;
import mundialfp.view.tables.paisABM.PaisTableSorter;
import mundialfp.view.tables.TableCustom1;
import mundialfp.view.tables.TableCustom2;
import mundialfp.view.tables.paisABM.TablePaisManager;
import uy.com.pzit.core.util.ImageUtil;
import uy.com.pzit.fpmundialmodel.web.ws.Competencia;
import uy.com.pzit.fpmundialmodel.web.ws.Encuentro;
import uy.com.pzit.fpmundialmodel.web.ws.Pais;
import uy.com.pzit.fpmundialmodel.web.ws.PaisEnCompeticion;

/**
 *
 * @author pferraz
 */
public class RegistrarEncuentro extends javax.swing.JFrame {

    private TableCustom1 tblListaPais;
    private PaisTableSorter paisTableSorter;
    private TablePaisManager tGenerator;
    int BANDERA_HEIGHT = 30;
    int BANDERA_WIDTH = 50;
    private int count = 1;
    private Map<String, Pais> nombrePaisMap;
    private List<Encuentro> encuentros;
    private String fase;
    private Competencia competencia;
    private EncuentroManager encuentroManager;

    /**
     * Creates new form RegistroEncuentro
     *
     * @param encuentros
     * @param fase
     * @param competencia
     * @param compTable
     * @param pManager
     */
    public RegistrarEncuentro(List<Encuentro> encuentros, String fase, Competencia competencia, TableCustom2 compTable, PrincipalManager pManager) {
        this.encuentroManager = new EncuentroManager(this, compTable, pManager);
        this.encuentros = encuentros;
        this.fase = fase;
        this.competencia = competencia;
        common();
    }

    public RegistrarEncuentro() {
        common();
    }

    private void common() {
        nombrePaisMap = new HashMap<>();
        tGenerator = new TablePaisManager();
        paisTableSorter = new PaisTableSorter();
        this.tblListaPais = new TableCustom1(2);
        initComponents();
        formLoad();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlRegistrarEncuentro = new javax.swing.JPanel();
        pnlListaPais = new javax.swing.JPanel();
        txtPaisQuickSearch = new javax.swing.JTextField();
        lblBanderaPais1 = new javax.swing.JLabel();
        lblBanderaPais2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        lblNombrePais1 = new javax.swing.JLabel();
        lblNombrePais2 = new javax.swing.JLabel();
        txtGolesPais1 = new javax.swing.JTextField();
        txtGolesPais2 = new javax.swing.JTextField();
        chkPenales = new javax.swing.JCheckBox();
        btnRegistrarEncuentro = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        lblLoad = new javax.swing.JLabel();
        lblBallLoad = new javax.swing.JLabel();

        setTitle("Registrar Encuentro");
        setName("frmRegistrarEncuentro"); // NOI18N
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        pnlRegistrarEncuentro.setBackground(java.awt.Color.white);
        pnlRegistrarEncuentro.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        pnlListaPais.setBackground(java.awt.Color.white);

        txtPaisQuickSearch.setFont(new java.awt.Font("Trebuchet MS", 0, 13)); // NOI18N
        txtPaisQuickSearch.setForeground(java.awt.Color.gray);
        txtPaisQuickSearch.setText("Búsqueda rápida ...");
        txtPaisQuickSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPaisQuickSearchFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPaisQuickSearchFocusLost(evt);
            }
        });

        javax.swing.GroupLayout pnlListaPaisLayout = new javax.swing.GroupLayout(pnlListaPais);
        pnlListaPais.setLayout(pnlListaPaisLayout);
        pnlListaPaisLayout.setHorizontalGroup(
            pnlListaPaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlListaPaisLayout.createSequentialGroup()
                .addComponent(txtPaisQuickSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 146, Short.MAX_VALUE))
        );
        pnlListaPaisLayout.setVerticalGroup(
            pnlListaPaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlListaPaisLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txtPaisQuickSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(453, 453, 453))
        );

        pnlRegistrarEncuentro.add(pnlListaPais, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, 328));

        lblBanderaPais1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlRegistrarEncuentro.add(lblBanderaPais1, new org.netbeans.lib.awtextra.AbsoluteConstraints(452, 37, 90, 50));

        lblBanderaPais2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlRegistrarEncuentro.add(lblBanderaPais2, new org.netbeans.lib.awtextra.AbsoluteConstraints(664, 37, 90, 50));

        jLabel1.setFont(new java.awt.Font("Trebuchet MS", 1, 24)); // NOI18N
        jLabel1.setText("VS");
        pnlRegistrarEncuentro.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(589, 48, -1, -1));

        lblNombrePais1.setFont(new java.awt.Font("Trebuchet MS", 1, 14)); // NOI18N
        lblNombrePais1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pnlRegistrarEncuentro.add(lblNombrePais1, new org.netbeans.lib.awtextra.AbsoluteConstraints(404, 95, 184, 20));

        lblNombrePais2.setFont(new java.awt.Font("Trebuchet MS", 1, 14)); // NOI18N
        lblNombrePais2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pnlRegistrarEncuentro.add(lblNombrePais2, new org.netbeans.lib.awtextra.AbsoluteConstraints(625, 95, 172, 20));

        txtGolesPais1.setFont(new java.awt.Font("Trebuchet MS", 1, 36)); // NOI18N
        txtGolesPais1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtGolesPais1.setText("0");
        txtGolesPais1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtGolesPais1ActionPerformed(evt);
            }
        });
        txtGolesPais1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtGolesPais1FocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtGolesPais1FocusLost(evt);
            }
        });
        pnlRegistrarEncuentro.add(txtGolesPais1, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 120, 53, 61));

        txtGolesPais2.setFont(new java.awt.Font("Trebuchet MS", 1, 36)); // NOI18N
        txtGolesPais2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtGolesPais2.setText("0");
        txtGolesPais2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtGolesPais2FocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtGolesPais2FocusLost(evt);
            }
        });
        pnlRegistrarEncuentro.add(txtGolesPais2, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 120, 53, 61));

        chkPenales.setBackground(java.awt.Color.white);
        chkPenales.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        chkPenales.setText("Penales");
        pnlRegistrarEncuentro.add(chkPenales, new org.netbeans.lib.awtextra.AbsoluteConstraints(589, 184, -1, 38));

        btnRegistrarEncuentro.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
        btnRegistrarEncuentro.setText("Registrar");
        btnRegistrarEncuentro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarEncuentroActionPerformed(evt);
            }
        });
        pnlRegistrarEncuentro.add(btnRegistrarEncuentro, new org.netbeans.lib.awtextra.AbsoluteConstraints(532, 248, 148, 43));

        btnLimpiar.setText("Limpiar");
        btnLimpiar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });
        pnlRegistrarEncuentro.add(btnLimpiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 300, 70, 20));

        lblLoad.setFont(new java.awt.Font("Trebuchet MS", 1, 10)); // NOI18N
        lblLoad.setText("REGISTRANDO");
        pnlRegistrarEncuentro.add(lblLoad, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 323, -1, 20));

        lblBallLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/211.GIF"))); // NOI18N
        pnlRegistrarEncuentro.add(lblBallLoad, new org.netbeans.lib.awtextra.AbsoluteConstraints(730, 270, -1, -1));

        getContentPane().add(pnlRegistrarEncuentro, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 350));

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtPaisQuickSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPaisQuickSearchFocusGained
        txtPaisQuickSearch.setText("");
        txtPaisQuickSearch.setForeground(Color.BLACK);
    }//GEN-LAST:event_txtPaisQuickSearchFocusGained

    private void txtPaisQuickSearchFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPaisQuickSearchFocusLost
        // TODO add your handling code here:
        if (txtPaisQuickSearch.getText().length() == 0) {
            txtPaisQuickSearch.setText("Búsqueda rápida ...");
            txtPaisQuickSearch.setForeground(Color.GRAY);
        }
    }//GEN-LAST:event_txtPaisQuickSearchFocusLost

    private void txtGolesPais1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtGolesPais1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtGolesPais1ActionPerformed

    private void txtGolesPais1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGolesPais1FocusLost
        // TODO add your handling code here:
        if (txtGolesPais1.getText().length() == 0) {
            txtGolesPais1.setText("0");
        }
    }//GEN-LAST:event_txtGolesPais1FocusLost

    private void txtGolesPais2FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGolesPais2FocusLost
        // TODO add your handling code here:
        if (txtGolesPais2.getText().length() == 0) {
            txtGolesPais2.setText("0");
        }
    }//GEN-LAST:event_txtGolesPais2FocusLost

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        // TODO add your handling code here:
        lblNombrePais1.setText("");
        lblNombrePais2.setText("");
        lblBanderaPais1.setIcon(null);
        lblBanderaPais2.setIcon(null);
        txtGolesPais1.setText("0");
        txtGolesPais2.setText("0");
        chkPenales.setSelected(false);
        count = 1;
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void btnRegistrarEncuentroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarEncuentroActionPerformed
        // TODO add your handling code here:
        String message;
        message = "Desea registrar\n" + lblNombrePais1.getText() + " " + txtGolesPais1.getText()
                + "\n \tvs\t \n" + lblNombrePais2.getText() + " " + txtGolesPais2.getText() + "\n"
                + ((chkPenales.isSelected()) ? "Con penales" : "Sin penales") + "\n?";
        if (JOptionPane.showConfirmDialog(null, message) == 0) {
            encuentroManager.registrarEncuentro();
        }
    }//GEN-LAST:event_btnRegistrarEncuentroActionPerformed

    private void txtGolesPais1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGolesPais1FocusGained
        // TODO add your handling code here:
        txtGolesPais1.setText("");
    }//GEN-LAST:event_txtGolesPais1FocusGained

    private void txtGolesPais2FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtGolesPais2FocusGained
        // TODO add your handling code here:
        txtGolesPais2.setText("");
    }//GEN-LAST:event_txtGolesPais2FocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RegistrarEncuentro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RegistrarEncuentro().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnRegistrarEncuentro;
    private javax.swing.JCheckBox chkPenales;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel lblBallLoad;
    private javax.swing.JLabel lblBanderaPais1;
    private javax.swing.JLabel lblBanderaPais2;
    private javax.swing.JLabel lblLoad;
    private javax.swing.JLabel lblNombrePais1;
    private javax.swing.JLabel lblNombrePais2;
    private javax.swing.JPanel pnlListaPais;
    private javax.swing.JPanel pnlRegistrarEncuentro;
    private javax.swing.JTextField txtGolesPais1;
    private javax.swing.JTextField txtGolesPais2;
    private javax.swing.JTextField txtPaisQuickSearch;
    // End of variables declaration//GEN-END:variables

    private void formLoad() {
        enableComponents(pnlRegistrarEncuentro, true);
        lblBallLoad.setVisible(false);
        lblLoad.setVisible(false);
        tblListaPais.requestFocus();
        tGenerator.createPaisTable("PaisABM", 210, 280, tblListaPais, pnlListaPais, txtPaisQuickSearch);

        PaisTableModel dTM = new PaisABMTableModel(0);
        tblListaPais.setModel(dTM);
        for (PaisEnCompeticion p : competencia.getPaises()) {
            nombrePaisMap.put(p.getPais().getNombre(), p.getPais());
            Object[] newRow = {new ImageIcon(ImageUtil.resizeImage(ImageUtil.decodeToImage(p.getPais().getBanderaB64()), BANDERA_WIDTH, BANDERA_HEIGHT)), p.getPais().getNombre()};
            dTM.addRow(newRow);
        }

        paisTableSorter.initQuickSearch(tblListaPais, txtPaisQuickSearch, BANDERA_HEIGHT + 5,1);

        /*Limita la cantidad de caracteres y solo deja ingresar numeros*/
        ((PlainDocument) txtGolesPais1.getDocument()).setDocumentFilter(new IntegerDocumentFilter(2));
        ((PlainDocument) txtGolesPais2.getDocument()).setDocumentFilter(new IntegerDocumentFilter(2));

        /*Configuro poder tener acciones con la tecla enter en la tabla*/
        final String solve = "enter";
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        tblListaPais.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(enter, solve);
        tblListaPais.getActionMap().put(solve, new EnterAction());
    }

    class EnterAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent e) {
            int IMG_WIDTH = 90;
            int IMG_HEIGHT = 50;
            BufferedImage originalImage;
            String nombre;
            ImageIcon icon;
            if (count < 3) {
                int idx = tblListaPais.getSelectedRow();
                if (count == 1) {
                    nombre = tblListaPais.getValueAt(idx, 1).toString();
                    originalImage = ImageUtil.decodeToImage(nombrePaisMap.get(nombre).getBanderaB64());
                    icon = new ImageIcon(ImageUtil.resizeImage(originalImage, IMG_WIDTH, IMG_HEIGHT));
                    icon.getImage().getScaledInstance(34, 14, Image.SCALE_FAST);

                    lblNombrePais1.setText(nombre);
                    lblBanderaPais1.setIcon(icon);
                    count++;
                } else {

                    nombre = tblListaPais.getValueAt(idx, 1).toString();
                    if (!lblNombrePais1.getText().equalsIgnoreCase(nombre)) {
                        originalImage = ImageUtil.decodeToImage(nombrePaisMap.get(nombre).getBanderaB64());
                        icon = new ImageIcon(ImageUtil.resizeImage(originalImage, IMG_WIDTH, IMG_HEIGHT));
                        icon.getImage().getScaledInstance(34, 14, Image.SCALE_FAST);

                        lblNombrePais2.setText(tblListaPais.getValueAt(idx, 1).toString());
                        lblBanderaPais2.setIcon(icon);
                        count++;
                    }
                }

            }

        }
    }

    public void enableComponents(Container container, boolean enable) {
        Component[] components = container.getComponents();
        for (Component component : components) {
            if (!enable) {
                if (component != lblBallLoad && component != lblLoad) {
                    component.setEnabled(enable);
                }
            } else {
                component.setEnabled(enable);
            }

            if (component instanceof Container) {
                enableComponents((Container) component, enable);
            }
        }
    }

    public Map<String, Pais> getNombrePaisMap() {
        return nombrePaisMap;
    }

    public Competencia getCompetencia() {
        return competencia;
    }

    public JCheckBox getChkPenales() {
        return chkPenales;
    }

    public JLabel getLblBallLoad() {
        return lblBallLoad;
    }

    public JLabel getLblLoad() {
        return lblLoad;
    }

    public JLabel getLblNombrePais1() {
        return lblNombrePais1;
    }

    public JLabel getLblNombrePais2() {
        return lblNombrePais2;
    }

    public JTextField getTxtGolesPais1() {
        return txtGolesPais1;
    }

    public JTextField getTxtGolesPais2() {
        return txtGolesPais2;
    }

    public List<Encuentro> getEncuentros() {
        return encuentros;
    }

    public String getFase() {
        return fase;
    }

    public JPanel getPnlRegistrarEncuentro() {
        return pnlRegistrarEncuentro;
    }

}
